<template>
	<view class="root-container">
		<view v-if="isLoaded" :class="hasComment ? 'item-container' : 'cmt-container item-margin-container'"
			class="item-container">
			<text class="item-title">{{blog.title}}</text>
			<text class="item-author">{{blog.user.nickName}}@{{blog.createTime}}</text>
			<rich-text :nodes="blog.content" class="item-content"></rich-text>
			<image :src="blog.picture" mode="widthFix" class="item-picture"></image>
			<view>
				<view v-for="(tag,idx) in blog.tags" :key="idx" class="item-tag">{{tag}}</view>
			</view>

			<image :src="blog.user.avatar" mode="aspectFill" class="item-avatar"></image>
			<view class="icon-container">
				<image v-if="hasGood" src="../../static/icons/ic_good_fill.png" class="icon"
					@click.stop="changeGood(blog.id,false)"></image>
				<image v-else src="../../static/icons/ic_good.png" class="icon" @click.stop="changeGood(blog.id,true)">
				</image>
				<text class="icon-text">{{blog.good}}</text>
				<image src="../../static/icons/ic_comment.png" class="icon"></image>
				<text class="icon-text">{{blog.comments.length}}</text>
				<image src="../../static/icons/ic_count.png" class="icon"></image>
				<text class="icon-text">{{blog.readCount}}</text>
			</view>
		</view>
		<view v-if="hasComment" class="comments-container">
			<view v-for="(item,index) in parents" :key="item.id">
				<!-- 根评论和子评论的容器 -->
				<view class="cmt-container">
					<text class="cmt-author">{{item.nickName}}</text>
					<text class="cmt-time">{{item.createTime}}</text>
					<text class="cmt-content" @click="clickToReply(item)">{{item.content}}</text>
					<image :src="item.avatar" mode="aspectFill" class="cmt-avatar"></image>
				</view>
				<view v-if="replies[index].length > 0" class="replies-container">
					<view class="reply-item" v-for="(reply,idx) in replies[index]" :key="reply.id">
						<view class="reply-info">
							<text class="reply-author">{{reply.nickName}}:</text>
							<text class="reply-to">@{{reply.toUesr}}</text>
							<text class="reply-time">{{reply.createTime}}</text>
						</view>
						<text class="reply-content" @click="clickToReply(reply)">{{reply.content}}</text>
					</view>
				</view>
				<view v-if=" index < parents.length - 1" class="cmt-line">
				</view>
			</view>
		</view>
		<view class="input-container">
			<image :src="avatar" mode="aspectFill" class="input-avatar" @click="clickToLogin"></image>
			<textarea v-model="inputValue" :placeholder="inputHolder" placeholder-class="input-holder" auto-height
				@input="inputGetComment" class="input-area" />
			<text class="iconfont icon-fasong input-commit" @click="clickCommit"></text>
		</view>
		<login-dialog ref="login" @after="afterLogin"></login-dialog>
	</view>
</template>

<script>
	let parentId = null
	let cmtValue = ""
	let app = getApp()
	export default {
		data() {
			return {
				blog: {},
				hasGood: false,
				isLoaded: false,
				hasComment: false,
				parents: [], // 跟评论集合

				replies: [], // 子评论集合的集合
				avatar: '../../static/icons/default_user.png',
				inputHolder: "请输入评论内容",
				inputValue: "",
				good_ids:[]

			}
		},
		onLoad(options) {
			let id = options.id
			let good_ids = uni.getStorageSync(this.$params.Key_good_ids)
			if (good_ids) {
				this.hasGood = good_ids.indexOf(id) >= 0
			}
			this.addReadCount(id)
			let prefix = app.globalData.token.length == 0 ? '' : this.$params.host
			this.avatar = prefix + app.globalData.avatar
			this.$noti.add(this.$params.noti_login_status, this, this.afterLogin)
		},
		onUnload() {
			this.$noti.remove(this.$params.noti_login_status, this)
		},
		methods: {
			clickCommit() {
				if (app.globalData.token.length == 0) {
					this.$refs.login.show()
					return
				}
				if (cmtValue.trim().length == 0) {
					uni.showToast({
						title: '请输入评论内容',
						icon: 'none'
					});
					return
				}
				let url = this.$params.host + this.$params.action_add_comment
				let data = {
					blog_id: this.blog.id,
					token: app.globalData.token,
					parent_id: parentId,
					nick_name: app.globalData.nickName,
					email: app.globalData.email,
					is_owner: app.globalData.uid == this.blog.user.id,
					content: cmtValue,
					avatar: "/" + app.globalData.avatar
				}
				this.$request.post(url, data, res => {
					console.log(666, res);
					let cmt = res.data
					// this.blog.comments.push(cmt)
					this.blog.comments = [...this.blog.comments, cmt]
					this.formatComments(this.blog.comments)
					this.hasComment = this.blog.comments.length > 0
					this.inputHolder = "请输入评论内容..."
					this.inputValue = ""
					let pages = getCurrentPages()
					let prev = pages[pages.length - 2]
					prev.refreshComment(cmt)
					cmtValue = ""
					parentId = null
				})
			},
			clickToLogin() {
				this.$refs.login.show()
			},
			afterLogin(logout) {
				//let app = getApp()
				this.avatar = this.$params.host + app.globalData.avatar
			},
			inputGetComment(e) {
				cmtValue = e.detail.value
			},
			clickToReply(item) {
				parentId = item.id
				this.inputHolder = "@" + item.nickName
			},
			addReadCount(id) {
				let url = this.$params.host + this.$params.action_add_count
				let data = {
					id: id
				}
				this.$request.postParams(url, data, res => {
					let count = res.data.data
					// let pages = getCurrentPages()
					// let indexPage = pages[pages.length - 2]
					// indexPage.refreshCount(id, count)
					let args = {
						id: id,
						count: count
					}
					this.$noti.post(this.$params.noti_blog_count, args)


					this.getBlog(id)
				})
			},
			getBlog(id) {

				let url = this.$params.host + this.$params.action_blog + id

				this.$request.get(url, res => {
					this.blog = res.data.data

					uni.setNavigationBarTitle({

						title: this.blog.user.nickName
					})
					if (!this.blog.picture.startsWith('http')) {
						this.blog.picture = this.$params.host + this.blog.picture
					}
					if (!this.blog.user.avatar.startsWith('http')) {
						this.blog.user.avatar = this.$params.host + this.blog.user.avatar
					}

					this.blog.content = this.blog.content.replace(/\<img/gi, '<img class="rich-img" ')
					this.blog.createTime = this.$utils.formatTime(new Date(this.blog.createTime))
					this.blog.updateTime = this.$utils.formatTime(new Date(this.blog.updateTime))
					this.isLoaded = true

					// this.blog.comments.forEach(item=>{
					// 	if(!item.avatar.startsWith("http")){
					// 		item.avatar=this.$params.host+item.avatar
					// 	}
					// 	item.createTime=this.$utils.formatTime(new Date(item.createTime))
					// })

					this.hasComment = this.blog.comments.length > 0
					// this.parents = this.blog.comments
					this.formatComments(this.blog.comments)

				})
			},
			formatComments(comments) {
				if (comments.length == 0) {
					return
				}
				this.parents = []
				comments.forEach(item => {
					if (!item.avatar.startsWith("http")) {
						item.avatar = this.$params.host + item.avatar
					}
					item.createTime = this.$utils.formatTime(new Date(item.createTime))
					if (item.parentId == null) {
						this.parents.push(item)
					}
				})
				this.parents.sort(function(c1, c2) {
					return new Date(c2.createTime) - new Date(c1.createTime)
				})
				this.replies = new Array(this.parents.length).fill([])
				let index = 0
				this.parents.forEach(root => {
					let children = []
					children = children.concat(this.getAllChildren(root, comments))
					this.replies[index++] = children
					comments = comments.filter(c => children.every(cc => cc.id != c.id))
				})
			},
			getAllChildren(root, comments) {
				let results = []
				comments.forEach(c => {
					if (c.parentId == root.id) {
						c.toUesr = root.nickName
						results = results.concat(c)
						let cmts = comments.filter(cmt => cmt.id != c.id)
						let grandson = this.getAllChildren(c, comments)
						results = results.concat(grandson)
					}
				})
				return results
			},
			// changeGood(id, idGood) {

			// },
			changeGood(id, hasGood) { //点赞2

				this.hasGood = hasGood
			 // this.uni.setStorageSync(this.$params.key_good_id,hasGood)
				if (hasGood) {
					this.good_ids.push(id) //push要添加到数组末尾的元素。

				} else {
					let index = this.good_ids.indexOf(id) //indexOf返回数组中可以找到指定元素的第一个索引号。如果元素不存在，则返回-1。
					if (index > -1) {

						this.good_ids.splice(index, 1) //splice要添加到数组中的元素。如果不指定任何元素，splice只会从数组中删除元素。
					}
				}
				uni.setStorageSync(this.$params.Key_good_ids, this.good_ids)

				this.switchGood(id, hasGood)
			},
			switchGood(id, hasGood) {//2
				this.hasGood = hasGood
				// console.log(this.hasGood);
				let good_ids = uni.getStorageSync(this.$params.Key_good_ids)
				//todo:根据hasGood发送不同的请求到服务器
				// console.log(hasGood);
				let action = hasGood ? this.$params.action_good : this.$params.action_del_good
				let url = this.$params.host + action
				let data = {
					"id": id
				}
				this.$request.postParams(url, data, res => {
					this.blog.good = res.data.data
					let count = this.blog.good
					let ids = this.good_ids
					let arg = {
						id: id,
						count: count,
						ids: ids,
					}
					this.$noti.post(this.$params.blog_good_count, arg)
				})
			},

		}
	}
</script>

<style>
	@import url("blog.css");
</style>
